<template>
  <div class="login-container">
    <div class="login-icon">
      <van-icon name="manager" size="60"/>
    </div>
    <div class="login-box">
      <van-form ref="form" @submit="onSubmit">
        <van-field
          v-model="username"
          name="username"
          placeholder="请输入用户名"
          :rules="rules.username"
        />
        <van-field
          v-model="password"
          name="password"
          placeholder="请输入密码"
          :rules="rules.password"
        />
        <div style="margin: 16px;">
          <van-button round block type="info" native-type="submit" :loading="submitting" loading-text="登录中...">登录</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { Toast, Field, Button, Form } from 'vant'
import validate from '@/common/validate.js'

Vue.use(Toast)
Vue.use(Field)
Vue.use(Button)
Vue.use(Form)

const rules = {
  username: [
    { required: true, message: '请输入用户名' },
    ...validate.username
  ],
  password: [
    { required: true, message: '请输入密码' },
    ...validate.password
  ]
}

export default {
  name: 'Login',
  data () {
    return {
      username: '',
      password: '',
      rules: rules,
      submitting: false
    }
  },
  created () {
    console.log(this.$route.params.redirect)

    if (this.$route.params.redirect) {
      this.$toast('请先登录用户')
    }
  },
  methods: {
    onSubmit (values) {
      if (this.submitting) return

      this.submitting = true

      const formData = new FormData()
      for (const key in values) {
        formData.append(key, values[key])
      }

      this.$store.dispatch('login', formData)
        .then(() => {
          this.$store.dispatch('fetchUser')
            .then(() => {
              this.submitting = false
              this.$router.replace({ path: this.$route.params.redirect })
            })
            .catch(() => {
              this.$toast('获取用户信息失败')
            })
        })
        .catch(() => {
          this.submitting = false
          this.$toast('用户名或密码错误')
        })
    }
  }
}
</script>

<style lang="less">
  .login-box {
    margin-top: 80px;
    padding: 0 10px;
  }

  .login-icon {
    width: 80px;
    height: 80px;
    background: #ccc;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 40px;
    margin: 0 auto;
    margin-top: 80px;
  }
</style>
